Jan 8, 2024
cust_data() function):city.txt file:count_lines() function):display_oddLines() function):def count_words_and_statements(filename):
with open(filename, 'r') as file:
content = file.read()
words = len(content.split())
statements = content.count('.') + content.count('!') + content.count('?')
print(f"Number of words: {words}")
print(f"Number of statements: {statements}")
# Example usage:
count_words_and_statements('your_file.txt')def pager(filename):
with open(filename, 'r') as file:
lines = file.readlines()
total_lines = len(lines)
start = 0
end = min(25, total_lines)
while start < total_lines:
for i in range(start, end):
print(lines[i], end='')
user_input = input("Enter 'continue' to show the next 25 lines or 'stop' to close the file: ")
if user_input.lower() == 'stop':
break
start += 25
end = min(start + 25, total_lines)
# Example usage:
pager('your_file.txt')Note: If user enters same characters multiple times in a string, then word from file will only be eligible for output if it contains that character for same or more number of times in it. (if file have apple, greenapple and user’s string is ‘aepe’ then output will only be greenapple. apple is not eligible as it contains e for 1 time only.
def find_words_in_file(user_string, filename):
user_char_count = {}
for char in user_string:
user_char_count[char] = user_char_count.get(char, 0) + 1
eligible_words = []
with open(filename, 'r') as file:
for line in file:
words = line.strip().split()
for word in words:
word_char_count = {}
for char in word:
word_char_count[char] = word_char_count.get(char, 0) + 1
is_eligible = True
for char, count in user_char_count.items():
if char not in word_char_count or word_char_count[char] < count:
is_eligible = False
break
if is_eligible:
eligible_words.append(word)
return eligible_words
# Example usage:
user_input = input("Enter your string: ")
result = find_words_in_file(user_input, 'your_file.txt')
print("Eligible words:", result)Examples: If data file one contains the following data: Friends are crazy, Friends are naughty ! Friends are honest, Friends are best !
Output 1:
! tseb era sdneirF ,tsenoh era sdneirF
! ythguan era sdneirF ,yzarc era sdneirF
Output 2:
! TSEB ERA SDNEIRF ,TSENOH ERA SDNEIRF
! YTHGUAN ERA SDNEIRF ,YZARC ERA SDNEIRF
Output 3:
Vowels = 22
Output 4:
! YTHGUAN ERA SDNEIRF ,YZARC ERA SDNEIRF
def reverse_file(input_file, output_file):
with open(input_file, 'r') as f:
content = f.read()
reversed_content = content[::-1]
with open(output_file, 'w') as f:
f.write(reversed_content)
def convert_to_uppercase(input_file, output_file):
with open(input_file, 'r') as f:
content = f.read()
uppercase_content = content.upper()
with open(output_file, 'w') as f:
f.write(uppercase_content)
def count_vowels(input_file):
with open(input_file, 'r') as f:
content = f.read()
vowels = 'aeiouAEIOU'
vowel_count = sum(1 for char in content if char in vowels)
print(f'Vowels = {vowel_count}')
def print_second_line(input_file):
with open(input_file, 'r') as f:
lines = f.readlines()
if len(lines) >= 2:
second_line = lines[1].strip()
print(second_line)
# Example usage:
file_one = 'file_one.txt'
file_two = 'file_two.txt'
file_three = 'file_three.txt'
reverse_file(file_one, file_two)
convert_to_uppercase(file_two, file_three)
count_vowels(file_three)
print_second_line(file_three)def extract_four_letter_words(filename):
with open(filename, 'r') as file:
words = file.read().split()
result_words = [word for word in words if len(word) == 4 and word[0] == word[-1]]
return result_words
# Example usage:
filename = 'text_file.txt'
result = extract_four_letter_words(filename)
print(result)Example: If value in text file is : ‘INDIA IS MY COUNTRY’
Output will be: ‘AIDNI SI MY COUNTRY’"
Input:
Python is a Easy Subject
OOPs is One of the most
interesting Topic
Output:
No of space: 10
No of word: 13
No of character: 64
"
def count_stats(filename):
with open(filename, 'r') as file:
content = file.read()
word_count = len(content.split())
char_count = len(content)
space_count = content.count(' ')
print(f'No of space: {space_count}')
print(f'No of word: {word_count}')
print(f'No of character: {char_count}')
# Example usage:
filename = 'text_file.txt'
count_stats(filename)Text file1 content:
Friends are crazy, Friends are naughty !
#Friends are honest, Friends are best !
Friends are like keygen, #friends are like license key !
We are nothing without friends, Life is not possible without friends !
Text file2 shoud be:
Friends are crazy, Friends are naughty !
Friends are like keygen,
We are nothing without friends, Life is not possible without friends !"
def filter_comments(input_filename, output_filename):
with open(input_filename, 'r') as input_file:
lines = input_file.readlines()
filtered_lines = [line for line in lines if not line.startswith('#')]
with open(output_filename, 'w') as output_file:
output_file.writelines(filtered_lines)
# Example usage:
input_filename = 'file1.txt'
output_filename = 'file2.txt'
filter_comments(input_filename, output_filename)
# Display data of file2
with open(output_filename, 'r') as f:
print(f.read())Example:
Enter Something (for quit enter END):Hi Friends
Enter Something (for quit enter END):how are you all
Enter Something (for quit enter END):I am fine
Enter Something (for quit enter END):hope you all are fine
Enter Something (for quit enter END):END
The Line started with Capital Letters:
Hi Friends
I am fine"
filename = 'user_lines.txt'
with open(filename, 'w') as file:
while True:
user_input = input("Enter Something (for quit enter END): ")
if user_input.upper() == 'END':
break
file.write(user_input + '\n')
with open(filename, 'r') as file:
lines = file.readlines()
capital_lines = [line.strip() for line in lines if line[0].isupper()]
print("The Line started with Capital Letters:")
print('\n'.join(capital_lines))Example:
File 1: python1.txt
Friends are crazy, Friends are naughty !
Friends are honest, Friends are best !
Friends are like keygen, friends are like license key !
new We are nothing without friends, Life is not possible without friends !
File 2: python2.txt
Friends are crazy, Friends are naughty !
Friends 6re honest, Friends are best !
Friends are like keygen, friends are like license key !
new We are nothing without friends, Life is not possible without friends !
Output:
line number 2 colNo. 9"
def compare_files(file1, file2):
with open(file1, 'r') as f1, open(file2, 'r') as f2:
line_num = 1
while True:
line1 = f1.readline()
line2 = f2.readline()
if not line1 and not line2:
break
col_num = 1
for char1, char2 in zip(line1, line2):
if char1 != char2:
print(f"Difference at line number {line_num}, colNo. {col_num}")
return
col_num += 1
if len(line1) != len(line2):
print(f"Difference at line number {line_num}, colNo. {col_num}")
return
line_num += 1
# Example usage:
file1 = 'python1.txt'
file2 = 'python2.txt'
compare_files(file1, file2)Example: File 1: python1.txt Friends are crazy, Friends are naughty ! Friends are honest, Friends are best ! Friends are like keygen, friends are like license key ! new We are nothing without friends, Life is not possible without friends ! Output: Friends - 5,are - 7,crazy, - 1,naughty - 1,! - 4,honest, - 1,best - 1,like - 2,keygen, - 1,friends - 2,license - 1,key - 1,new - 1,We - 1,nothing - 1,without - 2,friends, - 1,Life - 1,is - 1,not - 1,possible - 1,”
def count_word_frequency(filename):
with open(filename, 'r') as file:
words = file.read().split()
word_frequency = {}
for word in words:
if word in word_frequency:
word_frequency[word] += 1
else:
word_frequency[word] = 1
for word, count in word_frequency.items():
print(f'{word} - {count}')
# Example usage:
filename = 'python1.txt'
count_word_frequency(filename)# string_functions.py
def reverse_string(s):
return s[::-1]
def uppercase_string(s):
return s.upper()
def count_vowels(s):
vowels = 'aeiouAEIOU'
return sum(1 for char in s if char in vowels)
# main.py
from string_functions import reverse_string, uppercase_string, count_vowels
user_input = input("Enter a string: ")
reversed_str = reverse_string(user_input)
print(f"Reversed String: {reversed_str}")
uppercase_str = uppercase_string(user_input)
print(f"Uppercase String: {uppercase_str}")
vowel_count = count_vowels(user_input)
print(f"Vowel Count: {vowel_count}")# cal.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
return "Cannot divide by zero"
# main.py
from cal import add, subtract, multiply, divide
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result_add = add(num1, num2)
print(f"Addition: {result_add}")
result_subtract = subtract(num1, num2)
print(f"Subtraction: {result_subtract}")
result_multiply = multiply(num1, num2)
print(f"Multiplication: {result_multiply}")
result_divide = divide(num1, num2)
print(f"Division: {result_divide}")Input: ‘This is Python Programming’
Output: ‘This’"
Input:
# Hello LJ
Wish you happy Republic #Day
Happy 74th Republic Day
What a #Parade at Kartavya Path
Very Happy after watching that parade
Output:
Wish you happy Republic
Happy 74th Republic Day
What a
Very Happy after watching that parade
"
class Student:
def __init__(self, student_name, marks):
self.student_name = student_name
self.marks = marks
# Create an instance
student_instance = Student("John", 85)
# Print original values
print(f"Original values: {student_instance.student_name}, {student_instance.marks}")
# Modify attribute values
student_instance.student_name = "Jane"
student_instance.marks = 90
# Print modified values
print(f"Modified values: {student_instance.student_name}, {student_instance.marks}")Original values: John, 85
Modified values: Jane, 90
class Student:
def __init__(self, student_id, student_name):
self.student_id = student_id
self.student_name = student_name
self.student_class = None
def display_attributes(self):
print(f"ID: {self.student_id}, Name: {self.student_name}, Class: {self.student_class}")
# Create an instance
student_instance = Student(1, "John")
# Set the student_class attribute
student_instance.student_class = "Grade 10"
# Display attributes
student_instance.display_attributes()ID: 1, Name: John, Class: Grade 10
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
# Create an instance
rectangle_instance = Rectangle(5, 8)
# Compute the area
area = rectangle_instance.area()
print(f"Area of the rectangle: {area}")Area of the rectangle: 40
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * (self.radius ** 2)
def perimeter(self):
return 2 * math.pi * self.radius
# Create an instance
circle_instance = Circle(4)
# Compute area and perimeter
area = circle_instance.area()
perimeter = circle_instance.perimeter()
print(f"Area of the circle: {area}")
print(f"Perimeter of the circle: {perimeter}")Area of the circle: 50.26548245743669
Perimeter of the circle: 25.132741228718345
def check_positive_number(num):
if num <= 0:
raise ValueError("Number must be positive")
try:
user_input = int(input("Enter a positive number: "))
check_positive_number(user_input)
print("Valid input!")
except ValueError as e:
print(f"Error: {e}")Enter a positive number: -3
Error: Number must be positive
class CustomException(Exception):
pass
def check_even_number(num):
if num % 2 != 0:
raise CustomException("Number must be even")
try:
user_input = int(input("Enter an even number: "))
check_even_number(user_input)
print("Valid input!")
except CustomException as ce:
print(f"Error: {ce}")Enter an even number: 3
Error: Number must be even
accept-This method takes details from the user like name, roll number, and marks for two different subjects.
display-This method displays the details of every student.
search-This method searches for a particular student from the list of students. This method will ask the user for roll number and then search according to the roll number
delete-This method deletes the record of a particular student with a matching roll number.
update-This method updates the roll number of the student. This method will ask for the old roll number and new roll number. It will replace the old roll number with a new roll number.
The following instructions need to be considered while making a program.
1. Give class name as Student
2. Include methods name as accept, display, search, delete and update. (1 mark for each correct method to be formed).
3. Also form constructor with __init__ () method (2 marks for forming constructor).
4. 2 marks for correct object prepared like after deletion of one roll no of student it should update the list with new roll no. and should display it.
The example is just for understanding but logic should be for any n number of students.
For Example:
List of Students
Name : A
RollNo : 1
Marks1 : 100
Marks2 : 100
Name : B
RollNo : 2
Marks1 : 90
Marks2 : 90
class Student:
def __init__(self):
self.students = []
def accept(self):
name = input("Enter student name: ")
roll_no = int(input("Enter roll number: "))
marks1 = int(input("Enter marks for subject 1: "))
marks2 = int(input("Enter marks for subject 2: "))
student_data = {"Name": name, "RollNo": roll_no, "Marks1": marks1, "Marks2": marks2}
self.students.append(student_data)
print("Student details accepted successfully!")
def display(self):
print("\nList of Students:")
for student in self.students:
print(f"Name : {student['Name']}")
print(f"RollNo : {student['RollNo']}")
print(f"Marks1 : {student['Marks1']}")
print(f"Marks2 : {student['Marks2']}\n")
def search(self, roll_no):
for student in self.students:
if student['RollNo'] == roll_no:
print("Student found:")
print(f"Name : {student['Name']}")
print(f"RollNo : {student['RollNo']}")
print(f"Marks1 : {student['Marks1']}")
print(f"Marks2 : {student['Marks2']}")
return
print("Student not found.")
def delete(self, roll_no):
for student in self.students:
if student['RollNo'] == roll_no:
self.students.remove(student)
print("Student deleted successfully.")
return
print("Student not found.")
def update(self, old_roll_no, new_roll_no):
for student in self.students:
if student['RollNo'] == old_roll_no:
student['RollNo'] = new_roll_no
print("Student roll number updated successfully.")
return
print("Student not found.")
# Example usage:
student_system = Student()
# Accepting students
student_system.accept()
student_system.accept()
# Displaying students
student_system.display()
# Searching for a student
student_system.search(1)
# Deleting a student
student_system.delete(1)
# Updating a student's roll number
student_system.update(2, 3)
# Displaying updated list
student_system.display()Enter student name: rohan
Enter roll number: 12
Enter marks for subject 1: 10
Enter marks for subject 2: 20
Student details accepted successfully!
Enter student name: rohan
Enter roll number: 13
Enter marks for subject 1: 30
Enter marks for subject 2: 40
Student details accepted successfully!
List of Students:
Name : rohan
RollNo : 12
Marks1 : 10
Marks2 : 20
Name : rohan
RollNo : 13
Marks1 : 30
Marks2 : 40
Student not found.
Student not found.
Student not found.
List of Students:
Name : rohan
RollNo : 12
Marks1 : 10
Marks2 : 20
Name : rohan
RollNo : 13
Marks1 : 30
Marks2 : 40
Class Pizza containing
1. init method: to initialize the size (small, medium, large), toppings (corn, tomato, onion, capsicum, mushroom, olives, broccoli), cheese (mozzarella, feta, cheddar). Note: One pizza can have only one size but many toppings and cheese. (1.5 marks)
Throw custom exceptions if the selects toppings or cheese not available in lists given above. (1 mark)
2. price method: to calculate the prize of the pizza in the following way:
small = 50, medium = 100, large = 200
Each topping costs 20 rupees extra, except broccoli, olives and mushroom, which are exotic and so cost 50 rupees each.
Each type of cheese costs an extra 50 rupees. (1.5 marks)
Class Order containing
1. init method: to initialize the name, customerid of the customer who placed the order (0.5 marks)
2. order method: to allow the customer to select pizzas with choice of toppings and cheese (1 mark)
3. bill method: to generate details about each pizza ordered by the customer and the total cost of the order. (2 marks)
*Note: A customer can get multiple pizzas in one order.
class InvalidToppingException(Exception):
pass
class InvalidCheeseException(Exception):
pass
class Pizza:
def __init__(self, size, toppings, cheese):
self.size = size
self.toppings = toppings
self.cheese = cheese
self.validate_toppings()
self.validate_cheese()
def validate_toppings(self):
valid_toppings = ['corn', 'tomato', 'onion', 'capsicum', 'mushroom', 'olives', 'broccoli']
for topping in self.toppings:
if topping not in valid_toppings:
raise InvalidToppingException(f"Invalid topping: {topping}")
def validate_cheese(self):
valid_cheese = ['mozzarella', 'feta', 'cheddar']
for cheese in self.cheese:
if cheese not in valid_cheese:
raise InvalidCheeseException(f"Invalid cheese: {cheese}")
def price(self):
size_price = {'small': 50, 'medium': 100, 'large': 200}
topping_price = 20
exotic_toppings_price = 50
cheese_price = 50
total_price = size_price[self.size]
for topping in self.toppings:
if topping in ['broccoli', 'olives', 'mushroom']:
total_price += exotic_toppings_price
else:
total_price += topping_price
total_price += len(self.cheese) * cheese_price
return total_price
class Order:
def __init__(self, name, customer_id):
self.name = name
self.customer_id = customer_id
self.pizzas = []
def order(self, pizza):
self.pizzas.append(pizza)
def bill(self):
total_cost = 0
print(f"Order details for customer {self.name} (ID: {self.customer_id}):")
for index, pizza in enumerate(self.pizzas, start=1):
print(f"\nPizza {index}:")
print(f"Size: {pizza.size}")
print(f"Toppings: {', '.join(pizza.toppings)}")
print(f"Cheese: {', '.join(pizza.cheese)}")
pizza_cost = pizza.price()
print(f"Cost: {pizza_cost} rupees")
total_cost += pizza_cost
print(f"\nTotal Order Cost: {total_cost} rupees")
# Example usage:
try:
pizza1 = Pizza('medium', ['corn', 'tomato'], ['mozzarella', 'feta'])
pizza2 = Pizza('large', ['mushroom', 'olives'], ['cheddar'])
pizza3 = Pizza('small', ['onion', 'capsicum', 'broccoli'], ['mozzarella'])
order = Order("John Doe", 123)
order.order(pizza1)
order.order(pizza2)
order.order(pizza3)
order.bill()
except InvalidToppingException as ite:
print(f"Error: {ite}")
except InvalidCheeseException as ice:
print(f"Error: {ice}")Order details for customer John Doe (ID: 123):
Pizza 1:
Size: medium
Toppings: corn, tomato
Cheese: mozzarella, feta
Cost: 240 rupees
Pizza 2:
Size: large
Toppings: mushroom, olives
Cheese: cheddar
Cost: 350 rupees
Pizza 3:
Size: small
Toppings: onion, capsicum, broccoli
Cheese: mozzarella
Cost: 190 rupees
Total Order Cost: 780 rupees
words_with_length(length) — returns a list of all the words of length length
starts_with(char1) — returns a list of all the words that start with char1
ends_with(char2) — returns a list of all the words that end with char2
palindromes() — returns a list of all the palindromes in the list
only(str1) — returns a list of the words that contain only those letters in str1
avoids(str2) — returns a list of the words that contain none of the letters in str2
Make Required object for WordPlay class and test all the methods.
For Example:
If input list entered by user is: ['apple', 'banana', 'find', 'dictionary', 'set', 'tuple', 'list', 'malayalam', 'nayan', 'grind', 'apricot']
words_with_length (5) should return ['apple', 'tuple', 'nayan', 'grind']
starts_with ('a') should return ['apple', 'apricot']
ends_with ('d') should return ['find', 'grind']
palindromes () should return ['malayalam', 'nayan']
only ('bna') should return ['banana']
avoids ('amkd') should return ['set', 'tuple', 'list'].
class WordPlay:
def __init__(self, word_list):
self.words = word_list
def words_with_length(self, length):
return [word for word in self.words if len(word) == length]
def starts_with(self, char1):
return [word for word in self.words if word[:len(char1)] == char1]
def ends_with(self, char2):
return [word for word in self.words if word[-len(char2):] == char2]
def palindromes(self):
return [word for word in self.words if word == word[::-1]]
def only(self, str1):
return [word for word in self.words if self.all_chars_in_word(str1, word)]
def avoids(self, str2):
return [word for word in self.words if not self.any_char_in_word(str2, word)]
@staticmethod
def all_chars_in_word(chars, word):
for char in chars:
char_found = False
for w_char in word:
if w_char == char:
char_found = True
break
if not char_found:
return False
return True
@staticmethod
def any_char_in_word(chars, word):
for char in chars:
for w_char in word:
if w_char == char:
return True
return False
# Example usage:
word_list = ['apple', 'banana', 'find', 'dictionary', 'set', 'tuple', 'list', 'malayalam', 'nayan', 'grind', 'apricot']
word_play = WordPlay(word_list)
print("Words with length 5:", word_play.words_with_length(5))
print("Words starting with 'a':", word_play.starts_with('a'))
print("Words ending with 'd':", word_play.ends_with('d'))
print("Palindromes:", word_play.palindromes())
print("Words containing only 'bna':", word_play.only('bna'))
print("Words avoiding 'amkd':", word_play.avoids('amkd'))Words with length 5: ['apple', 'tuple', 'nayan', 'grind']
Words starting with 'a': ['apple', 'apricot']
Words ending with 'd': ['find', 'grind']
Palindromes: ['malayalam', 'nayan']
Words containing only 'bna': ['banana']
Words avoiding 'amkd': ['set', 'tuple', 'list']
Sample Output:
enter no of items: 3
enter code of item: milk
enter cost of item: 30
enter code of item: apple
enter cost of item: 35
enter code of item: gems
enter cost of item: 40
Item Code Price
milk 30
apple 35
gems 40
Enter quantity of each item:
Enter quantity of milk : 2
Enter quantity of apple : 3
Enter quantity of gems : 4
************************Bill**********************
ITEM PRICE QUANTITY SUBTOTAL
milk 30 2 60
apple 35 3 105
gems 40 4 160
**************************************
Total= 325
class Store:
def __init__(self):
self.products = {}
def add_product(self, code, price):
self.products[code] = price
def display_menu(self):
print("Item Code\t Price")
for code, price in self.products.items():
print(f"{code}\t\t {price}")
def generate_bill(self, quantities):
print("\n************************Bill**********************")
print("ITEM\t PRICE\t QUANTITY\t\t SUBTOTAL")
total_amount = 0
for code, quantity in quantities.items():
if code in self.products:
price = self.products[code]
subtotal = price * quantity
total_amount += subtotal
print(f"{code}\t {price}\t {quantity}\t\t\t {subtotal}")
print("**************************************************")
print(f"Total= {total_amount}")
# Example usage:
store = Store()
# Adding products to the store
store.add_product("milk", 30)
store.add_product("apple", 35)
store.add_product("gems", 40)
# Displaying the menu
store.display_menu()
# Taking input for quantities
num_items = int(input("Enter no of items: "))
quantities = {}
for _ in range(num_items):
code = input("Enter code of item: ")
quantity = int(input(f"Enter quantity of {code} : "))
quantities[code] = quantity
# Generating and displaying the bill
store.generate_bill(quantities)Item Code Price
milk 30
apple 35
gems 40
Enter no of items: 3
Enter code of item: milk
Enter quantity of milk : 2
Enter code of item: apple
Enter quantity of apple : 3
Enter code of item: gems
Enter quantity of gems : 4
************************Bill**********************
ITEM PRICE QUANTITY SUBTOTAL
milk 30 2 60
apple 35 3 105
gems 40 4 160
**************************************************
Total= 325
1. Add a method ‘distance from origin’ to class Point which returns the distance of the given point from origin. The equation is
2. Add a method ‘translate’ to class Point, which returns a new position of point after translation
3. Add a method ‘reflect_x’ to class Point, which returns a new point which is the reflection of the point about the x-axis.
4. Add a method ‘distance’ to return distance of the given point with respect to the other point. The formula for calculating distance between A(x1,y1) and B(x2,y2) is
After creating class blueprint run the following test case -
Test Case – Point (1,2)
Distance from origin - 2.23
Translate method - point (1,2) translated by (1,1) increment will be at (2,3) now
Reflect_x Method - Point (2,3) after given reflection will be at (2,-3)
Distance Method - distance between point (2,-3) and (3,4) is 1.41
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_from_origin(self):
return math.sqrt(self.x**2 + self.y**2)
def translate(self, dx, dy):
return Point(self.x + dx, self.y + dy)
def reflect_x(self):
return Point(self.x, -self.y)
def distance(self, other_point):
return math.sqrt((self.x - other_point.x)**2 + (self.y - other_point.y)**2)
# Test Case
point = Point(1, 2)
# Distance from origin
print(f"Distance from origin: {point.distance_from_origin():.2f}")
# Translate method
translated_point = point.translate(1, 1)
print(f"Translate method: Point ({point.x},{point.y}) translated by (1,1) is at ({translated_point.x},{translated_point.y}) now")
# Reflect_x method
reflected_point = point.reflect_x()
print(f"Reflect_x method: Point ({point.x},{point.y}) after given reflection is at ({reflected_point.x},{reflected_point.y})")
# Distance method
other_point = Point(3, 4)
print(f"Distance method: Distance between Point ({point.x},{point.y}) and ({other_point.x},{other_point.y}) is {point.distance(other_point):.2f}")Distance from origin: 2.24
Translate method: Point (1,2) translated by (1,1) is at (2,3) now
Reflect_x method: Point (1,2) after given reflection is at (1,-2)
Distance method: Distance between Point (1,2) and (3,4) is 2.83
A possible collection of classes which can be used to represent a music collection (for example, inside a music player), focusing on how they would be related by composition. You should include classes for songs, artists, albums and playlists. For simplicity you can assume that any song or album has a single “artist” value (which could represent more than one person), but you should include compilation albums (which contain songs by a selection of different artists). The “artist” of a compilation album can be a special value like “Various Artists”. You can also assume that each song is associated with a single album, but that multiple copies of the same song (which are included in different albums) can exist.Write a simple implementation of this model which clearly shows how the different classes are composed. Write some example code to show how you would use your classes to create an album and add all its songs to a playlist. Class Album should have a method to add track, class Artist should have methods to add album and add song, class Playlist should also have a method to add song.{.smaller}
class Song:
def __init__(self, title, duration):
self.title = title
self.duration = duration
self.album = None # Associated album
class Artist:
def __init__(self, name):
self.name = name
self.albums = [] # List of albums by the artist
self.songs = [] # List of individual songs by the artist
def add_album(self, album):
self.albums.append(album)
def add_song(self, song):
self.songs.append(song)
class Album:
def __init__(self, title, artist):
self.title = title
self.artist = artist
self.tracks = [] # List of tracks in the album
def add_track(self, song):
self.tracks.append(song)
song.album = self # Set the associated album for the song
class Playlist:
def __init__(self, title):
self.title = title
self.songs = [] # List of songs in the playlist
def add_song(self, song):
self.songs.append(song)
# Example usage:
# Create artists
artist1 = Artist("Artist1")
artist2 = Artist("Various Artists")
# Create songs
song1 = Song("Song1", 180)
song2 = Song("Song2", 200)
# Create albums
album1 = Album("Album1", artist1)
album1.add_track(song1)
album1.add_track(song2)
album2 = Album("Compilation Album", artist2)
album2.add_track(song1)
# Add albums to artists
artist1.add_album(album1)
artist2.add_album(album2)
# Create a playlist
playlist = Playlist("My Playlist")
# Add songs to the playlist
playlist.add_song(song1)
playlist.add_song(song2)
# Display information
print("Playlist:", playlist.title)
print("Songs in the playlist:")
for song in playlist.songs:
print(f"- {song.title} ({song.duration} seconds)")
# Display artists and their albums
print("\nArtists and their albums:")
for artist in [artist1, artist2]:
print(f"{artist.name}:")
for album in artist.albums:
print(f"- {album.title}")
# Display albums and their tracks
print("\nAlbums and their tracks:")
for album in [album1, album2]:
print(f"{album.title} by {album.artist.name}:")
for track in album.tracks:
print(f"- {track.title} ({track.duration} seconds)")1. make a constructor with a valid parameter
2. shift() returns the first element and removes it from the list. Also, use the custom(raise) exception in this method.
3. unshift() "pushes" a new element to the front or head of the list
4. push() adds a new element to the end of a list
5. pop() returns the last element and removes it from the list
6. remove() returns the maximum element of the list and removes it from the list.
7. Create the object and call all methods of the SQ class.
class EmptyListError(Exception):
pass
class SQ:
def __init__(self, initial_list=None):
self.items = initial_list or []
def shift(self):
if not self.items:
raise EmptyListError("Cannot shift from an empty list")
return self.items.pop(0)
def unshift(self, item):
self.items.insert(0, item)
def push(self, item):
self.items.append(item)
def pop(self):
if not self.items:
raise EmptyListError("Cannot pop from an empty list")
return self.items.pop()
def remove(self):
if not self.items:
raise EmptyListError("Cannot remove from an empty list")
max_element = max(self.items)
self.items.remove(max_element)
return max_element
def __str__(self):
return str(self.items).replace("[0, ", "[")
# Example usage:
sq = SQ([1, 2, 3, 4, 5])
# Shift
try:
print("Shifted:", sq.shift())
except EmptyListError as e:
print(e)
# Unshift
sq.unshift(0)
print("After Unshift:", sq)
# Push
sq.push(6)
print("After Push:", sq)
# Pop
try:
print("Popped:", sq.pop())
except EmptyListError as e:
print(e)
# Remove
try:
print("Removed Max Element:", sq.remove())
except EmptyListError as e:
print(e)
# Display final state
print("Final State:", sq)Shifted: 1
After Unshift: [2, 3, 4, 5]
After Push: [2, 3, 4, 5, 6]
Popped: 6
Removed Max Element: 5
Final State: [2, 3, 4]
Manish Patel